package cn.yuanqiao.web.controller.archive.xiaoxitongzhi;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.xiaoxitongzhi.domain.YqXxtz;
import cn.yuanqiao.archive.xiaoxitongzhi.service.IYqXxtzService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 消息通知Controller
 *
 * @author sy
 * @date 2023-10-10
 */
@RestController
@RequestMapping("/archive/yqXxtz")
public class YqXxtzController extends BaseController
{
    @Autowired
    private IYqXxtzService yqXxtzService;

    @Autowired
    private RemoteActivitiService remoteActivitiService;

    /**
     * 查询消息通知列表
     */
//    @RequiresPermissions("archive:yqXxtz:list")
    @GetMapping("/list")
    public TableDataInfo list(YqXxtz yqXxtz) {
//        startPage();
        List<YqXxtz> list = yqXxtzService.selectYqXxtzList(yqXxtz);
        return getDataTable(list);
    }

    /**
     * 判断是否有新消息
     */

    @PostMapping("/unread/messages")
    public AjaxResult UnreadMessages() {
        int i = yqXxtzService.selectYqXxtzCount();
        return AjaxResult.success(i);
    }

    /**
     * 导出消息通知列表
     */
//    @RequiresPermissions("archive:yqXxtz:export")
    @Log(title = "消息通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqXxtz yqXxtz) {
        List<YqXxtz> list = yqXxtzService.selectYqXxtzList(yqXxtz);
        ExcelUtil<YqXxtz> util = new ExcelUtil<YqXxtz>(YqXxtz.class);
        util.exportExcel(response, list, "消息通知数据");
    }

    /**
     * 获取消息通知详细信息
     */
//    @RequiresPermissions("archive:yqXxtz:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(yqXxtzService.selectYqXxtzById(id));
    }

    /**
     * 新增消息通知
     */
//    @RequiresPermissions("archive:yqXxtz:add")
    @Log(title = "消息通知", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqXxtz yqXxtz) {
        return toAjax(yqXxtzService.insertYqXxtz(yqXxtz));
    }

    /**
     * 修改消息通知
     */
//    @RequiresPermissions("archive:yqXxtz:edit")
    @Log(title = "消息通知", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqXxtz yqXxtz) {
        return toAjax(yqXxtzService.updateYqXxtz(yqXxtz));
    }

    @Log(title = "消息通知", businessType = BusinessType.UPDATE)
    @GetMapping("/updateApproveNoticeData")
    public AjaxResult updateApproveNoticeData() {
        R<List<Map<String, Object>>> taskListByUser = remoteActivitiService.getTaskListByUser();
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        YqXxtz query = new YqXxtz();
        //query.setRemark("REDIRECT:TASK");
        query.setType(3);
        query.setRecipientsId(userId);
        List<YqXxtz> yqXxtzs = yqXxtzService.selectYqXxtzListByRemark(query);
        if (yqXxtzs == null && yqXxtzs.size() == 0) {
            return AjaxResult.success("更新未读消息成功");
        }
        Map<Long, YqXxtz> yqXxtzMapByRecordId = yqXxtzs.stream().collect(Collectors.toMap(YqXxtz::getRecordId, Function.identity()));
        if (taskListByUser != null && taskListByUser.getCode() == 200 && taskListByUser.getData() != null) {
            List<Map<String, Object>> taskList = taskListByUser.getData();
            for (Map<String, Object> task : taskList) {
                String taskId = (String) task.get("taskId");
                String processInstanceId = (String) task.get("processInstanceId");
                String processInstanceName = (String) task.get("processInstanceName");
                String assignee = (String) task.get("assignee");
                Date createTime = (Date) task.get("createTime");
                YqXxtz yqXxtz = yqXxtzMapByRecordId.get(Long.valueOf(taskId));
                if (yqXxtz == null) {
                    yqXxtz = new YqXxtz();
                    yqXxtz.setId(SnowflakeIdGenerator.generateId());
                    yqXxtz.setRecipientsId(userId);
                    yqXxtz.setIsRead(0);
                    yqXxtz.setPublisherId(userId);
                    yqXxtz.setRecordId(Long.valueOf(taskId));
                    yqXxtz.setType(3);
                    yqXxtz.setCreateTime(createTime);
                    yqXxtz.setMsg("您有一条[" + processInstanceName + "]审批任务，请及时处理");
                    //yqXxtz.setRemark("REDIRECT:TASK");
                    yqXxtzService.insertYqXxtzAndYqXxfbfw(yqXxtz);
                } else {
                    yqXxtzMapByRecordId.remove(Long.valueOf(taskId));
                }
            }
        }
        if (yqXxtzMapByRecordId.size() != 0) {
            List<Long> idList = new ArrayList<>();
            yqXxtzMapByRecordId.entrySet().forEach(entry -> {
                Long id = entry.getValue().getId();
                idList.add(id);
            });
            int i = yqXxtzService.readYqXxtzByIds(idList.toArray(new Long[]{}));
        }
        //return toAjax(yqXxtzService.updateYqXxtz(yqXxtz));
        return AjaxResult.success("更新未读消息成功");
    }

    /**
     * 批量设置已读
     */
//    @RequiresPermissions("archive:yqXxtz:read")
    @Log(title = "消息通知", businessType = BusinessType.UPDATE)
    @PutMapping("/{ids}")
    public AjaxResult read(@PathVariable Long[] ids) {
        return toAjax(yqXxtzService.readYqXxtzByIds(ids));
    }

    /**
     * 全部设置已读
     */
//    @RequiresPermissions("archive:yqXxtz:read")
    @Log(title = "消息通知", businessType = BusinessType.UPDATE)
    @PutMapping("/allRead")
    public AjaxResult allRead() {
        return toAjax(yqXxtzService.readYqXxtzAll());
    }

    /**
     * 批量删除（已读消息）
     */
//    @RequiresPermissions("archive:yqXxtz:remove")
    @Log(title = "消息通知", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(yqXxtzService.deleteYqXxtzByIds(ids));
    }

    /**
     * 全部删除（已读消息）
     */
//    @RequiresPermissions("archive:yqXxtz:remove")
    @Log(title = "消息通知", businessType = BusinessType.DELETE)
    @DeleteMapping("/allRemove")
    public AjaxResult allRemove() {
        return toAjax(yqXxtzService.deleteYqXxtzAll());
    }

    @PostMapping("/addyqXxtzApi")
    public void addyqXxtzApi(@RequestParam("msg") String msg, @RequestParam("publisherId") Long publisherId, @RequestParam("recipientsId") Long recipientsId, @RequestParam("tenantCode") String tenantCode) {
        yqXxtzService.addyqXxtzApi(msg, publisherId, recipientsId, tenantCode);
    }
}
